package org.neu.ccs.secureim;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyPair;
import java.util.concurrent.ConcurrentHashMap;

/*
 * Class to encapsulate the server and its actions.
 */

public class ChatServer implements Runnable {

	boolean stop = false;
	int port;
	KeyPair pair;
	ConcurrentHashMap<String, ServerUserInfo> users;
	
	public ChatServer(int port, KeyPair serverPair, ConcurrentHashMap<String, ServerUserInfo> users2)
	{
		this.port = port;
		this.users = users2;
		pair = serverPair;
		
		SIMSSecurityManager manager = new SIMSSecurityManager();
		System.setSecurityManager(manager);
	}
	
	
	//Start server
	public void run()
	{
		ServerSocket sock = null;
		try
		{
			sock = new ServerSocket(port);
			sock.setPerformancePreferences(1, 0, 0);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		while( !stop )
		{
			try
			{
				Socket sessionSocket = sock.accept();
				ServerThread t = new ServerThread(sessionSocket, pair, users);
				Thread sthread = new Thread(t);
				sthread.start();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			catch(SecurityException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	//Stop server
	public void stop()
	{
		stop = true;
	}
}
